package com.kandinfo.survey.questionnaire.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kandinfo.base.common.dto.ResultDto;
import com.kandinfo.base.common.dto.ResultDtoFactory;
import com.kandinfo.base.common.service.AbstractService;
import com.kandinfo.base.security.SecurityContext;
import com.kandinfo.base.security.domain.User;
import com.kandinfo.survey.common.constants.StatusConstant;
import com.kandinfo.survey.common.domain.QuestionnaireDetail;
import com.kandinfo.survey.common.repository.QuestionnaireDetailRepository;
import com.kandinfo.survey.questionnaire.dto.QuestionnaireDetailRequestDto;
import com.kandinfo.survey.questionnaire.service.QuestionnaireDetailService;

@Service
public class QuestionnaireDetailServiceImpl
        extends AbstractService<QuestionnaireDetail, Long, QuestionnaireDetailRepository>
        implements QuestionnaireDetailService {

    @Override
    @Transactional
    public ResultDto connectQuesnaireQues(QuestionnaireDetailRequestDto requestDto) {
        if (requestDto == null) {
            return ResultDtoFactory.toNack(" 参数错误! ", Boolean.FALSE);
        }
        if (CollectionUtils.isEmpty(requestDto.getIdList())) {
            return ResultDtoFactory.toNack(" 题目id不能为空! ", Boolean.FALSE);
        }

        // get current user
        User currentUser = SecurityContext.getInstance().getCurrentUser();

        List<QuestionnaireDetail> saveDomains = new ArrayList<QuestionnaireDetail>();
        requestDto.getIdList().forEach(questionId -> {
            QuestionnaireDetail domain = new QuestionnaireDetail();
            domain.setCreateTs(new Date());
            domain.setCreateBy(currentUser == null ? 1L : currentUser.getId());
            domain.setQuestionnaireId(requestDto.getQuestionnaireId());
            domain.setQuestionId(questionId);
            domain.setStatus(StatusConstant.NORMALLY_USE);
            saveDomains.add(domain);
        });
        if (CollectionUtils.isNotEmpty(saveDomains)) {
            repository.save(saveDomains);
        }
        return ResultDtoFactory.toAck(" 试卷题目关联成功！ ", Boolean.TRUE);
    }

    @Override
    public List<QuestionnaireDetail> findOneByQuesnaireId(Long questionnaireId) {
        return repository.findOneDetailByQuesnaireId(questionnaireId);
    }

}
